package com.beyond.common.util

import android.content.Context
import android.content.SharedPreferences
import com.beyond.common.ext.toJson
import com.google.gson.Gson

/**
 * @author chen
 * @time 2023/5/31 10:26
 * @name SpUtil.kt
 * @class describe
 */
object SpUtil {
    private var sharedPreferences: SharedPreferences? = null
    private var gson: Gson? = null

    /**
     * @param context  ApplicationContext
     */
    fun init(context: Context) {
        sharedPreferences = context.getSharedPreferences("app_sp", Context.MODE_PRIVATE)
        gson = Gson()
    }

    private fun checkInit() {
        check(!(sharedPreferences == null || gson == null)) { "Please call init(context) first." }
    }

    fun putString(key: String?, data: String?) {
        sharedPreferences?.edit()?.putString(key, data)?.apply()
    }

    fun getString(context: Context, key: String?): String? {
        init(context)
        return sharedPreferences?.getString(key, "")
    }
    fun getString(key: String?): String? {
        return sharedPreferences?.getString(key, "")
    }

    fun putInt(key: String?, data: Int) {
        sharedPreferences?.edit()?.putInt(key, data)?.apply()
    }

    fun getInt(key: String?): Int {
        return sharedPreferences?.getInt(key, 0) ?: 0
    }

    fun getInt(key: String?, defaultValue: Int): Int {
        return sharedPreferences?.getInt(key, defaultValue) ?: 0
    }

    fun putBoolean(key: String?, data: Boolean) {
        sharedPreferences?.edit()?.putBoolean(key, data)?.apply()
    }

    fun getBoolean(key: String?, defaultData: Boolean): Boolean {
        return sharedPreferences?.getBoolean(key, defaultData) ?: false
    }

    fun putFloat(key: String?, data: Float) {
        sharedPreferences?.edit()?.putFloat(key, data)?.apply()
    }

    fun getFloat(key: String?, defaultData: Float): Float {
        return sharedPreferences?.getFloat(key, defaultData) ?: 0f
    }

    fun putLong(key: String?, data: Long) {
        sharedPreferences?.edit()?.putLong(key, data)?.apply()
    }

    fun getLong(key: String?, defaultData: Long): Long {
        return sharedPreferences?.getLong(key, defaultData) ?: 0L
    }

    fun clear() {
        sharedPreferences?.edit()?.clear()?.apply()
    }

    fun remove(key: String?) {
        sharedPreferences?.edit()?.remove(key)?.apply()
    }

    fun <T> putData(key: String?, data: T?) {
        checkInit()
        if (data != null) {
            sharedPreferences?.edit()?.putString(key, gson?.toJson(data))?.apply()
        }
    }

    fun <T> getData(key: String?, clz: Class<T>?): T? {
        checkInit()
        val json = sharedPreferences?.getString(key, "")
        return gson?.fromJson(json, clz)
    }
}